package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"

	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/server/web"
)

// MemberBalanceController 处理会员余额记录相关请求
type MemberBalanceController struct {
	web.Controller
}

// List 获取会员余额变动记录列表
func (c *MemberBalanceController) List() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 解析过滤条件
	filters := make(map[string]interface{})

	// 会员ID
	if memberId, err := c.GetInt64("member_id", 0); err == nil && memberId > 0 {
		filters["member_id"] = memberId
	}

	// 变动类型
	if logType, err := c.GetInt8("type", -1); err == nil && logType != -1 {
		filters["type"] = logType
	}

	// 订单号
	if orderNo := c.GetString("order_no"); orderNo != "" {
		filters["order_no"] = orderNo
	}

	// 交易流水号
	if transactionNo := c.GetString("transaction_no"); transactionNo != "" {
		filters["transaction_no"] = transactionNo
	}

	// 金额范围
	if minAmount, err := c.GetFloat("min_amount", -1); err == nil && minAmount >= 0 {
		filters["min_amount"] = minAmount
	}

	if maxAmount, err := c.GetFloat("max_amount", -1); err == nil && maxAmount > 0 {
		filters["max_amount"] = maxAmount
	}

	// 时间范围
	if startTime, err := c.GetInt64("start_time", 0); err == nil && startTime > 0 {
		filters["start_time"] = startTime
	}

	if endTime, err := c.GetInt64("end_time", 0); err == nil && endTime > 0 {
		filters["end_time"] = endTime
	}

	// 加盟商过滤
	if admin.FranchiseId > 0 {
		filters["franchise_id"] = admin.FranchiseId
	}

	// 获取余额变动记录列表
	balanceLogs, total, err := models.GetBalanceLogList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取余额变动记录列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回余额变动记录列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取余额变动记录列表成功",
		"data": map[string]interface{}{
			"list":  balanceLogs,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// Detail 获取余额变动记录详情
func (c *MemberBalanceController) Detail() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取记录ID
	id, err := c.GetInt64("id")
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的记录ID",
		}
		c.ServeJSON()
		return
	}

	// 获取余额变动记录详情，带加盟商权限验证
	balanceLog, err := models.GetBalanceLogById(id, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取余额变动记录详情失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取关联会员信息
	member, err := models.GetMemberById(balanceLog.MemberId, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回余额变动记录详情
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取余额变动记录详情成功",
		"data": map[string]interface{}{
			"log":    balanceLog,
			"member": member,
		},
	}
	c.ServeJSON()
}

// AdjustBalance 调整会员余额
func (c *MemberBalanceController) AdjustBalance() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取会员ID
	memberId, err := c.GetInt64("member_id")
	if err != nil || memberId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的会员ID",
		}
		c.ServeJSON()
		return
	}

	// 获取调整金额
	amount, err := c.GetFloat("amount")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的调整金额",
		}
		c.ServeJSON()
		return
	}

	// 获取调整原因
	description := c.GetString("description")
	if description == "" {
		description = "管理员余额调整"
	}

	// 获取会员信息，验证会员是否属于该加盟商
	member, err := models.GetMemberById(memberId, admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "会员不存在或不属于该加盟商",
		}
		c.ServeJSON()
		return
	}

	// 检查调整后的余额是否小于0
	if member.Balance+amount < 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "调整后余额不能小于0",
		}
		c.ServeJSON()
		return
	}

	// 调整会员余额
	err = models.UpdateMemberBalanceWithLogAndFranchise(
		memberId,
		amount,
		4, // 4:管理员调整
		"",
		"",
		description,
		admin.Username,
		admin.FranchiseId,
	)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "调整会员余额失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 记录操作日志
	models.CreateOperationLog(
		admin.Id,
		"调整会员余额",
		fmt.Sprintf("调整会员ID:%d的余额，金额:%.2f，原因:%s", memberId, amount, description),
		c.Ctx.Request.Method,
		c.Ctx.Input.IP(),
		admin.FranchiseId,
	)

	// 返回成功信息
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "调整会员余额成功",
	}
	c.ServeJSON()
}

// Stats 获取余额统计信息
func (c *MemberBalanceController) Stats() {
	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 计算各种统计数据，需要加盟商权限过滤
	o := orm.NewOrm()

	// 统计今日余额充值金额和笔数
	today := time.Now().Format("2006-01-02")
	startTime := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local).Unix()
	endTime := time.Now().Unix()

	// 今日充值总金额
	var todayRechargeAmount float64
	var todayRechargeCount int64
	var todayConsumeAmount float64
	var todayConsumeCount int64
	var totalBalanceAmount float64
	var memberCount int64

	// 如果是加盟商管理员，需要过滤数据
	if admin.FranchiseId > 0 {
		// 获取该加盟商下的所有会员ID
		var memberIds orm.ParamsList
		_, err := o.QueryTable(new(models.Member)).
			Filter("franchise_id", admin.FranchiseId).
			Filter("is_deleted", 0).
			ValuesFlat(&memberIds, "id")
		if err != nil || len(memberIds) == 0 {
			// 没有会员，返回空数据
			c.Data["json"] = map[string]interface{}{
				"success": true,
				"message": "获取余额统计信息成功",
				"data": map[string]interface{}{
					"today_recharge_amount": 0,
					"today_recharge_count":  0,
					"today_consume_amount":  0,
					"today_consume_count":   0,
					"total_balance_amount":  0,
					"member_count":          0,
				},
			}
			c.ServeJSON()
			return
		}

		// 今日充值统计
		err = o.Raw(`
			SELECT IFNULL(SUM(amount), 0) as total_amount, COUNT(*) as count 
			FROM ss_balance_log 
			WHERE member_id IN (?) AND type = 1 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, memberIds, startTime, endTime).QueryRow(&todayRechargeAmount, &todayRechargeCount)

		// 今日消费统计
		err = o.Raw(`
			SELECT IFNULL(SUM(ABS(amount)), 0) as total_amount, COUNT(*) as count 
			FROM ss_balance_log 
			WHERE member_id IN (?) AND type = 2 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, memberIds, startTime, endTime).QueryRow(&todayConsumeAmount, &todayConsumeCount)

		// 总余额统计
		err = o.Raw(`
			SELECT IFNULL(SUM(balance), 0) as total_balance, COUNT(*) as count 
			FROM ss_member 
			WHERE franchise_id = ? AND is_deleted = 0
		`, admin.FranchiseId).QueryRow(&totalBalanceAmount, &memberCount)
	} else {
		// 平台管理员，查看所有数据
		err = o.Raw(`
			SELECT IFNULL(SUM(amount), 0) as total_amount, COUNT(*) as count 
			FROM ss_balance_log 
			WHERE type = 1 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, startTime, endTime).QueryRow(&todayRechargeAmount, &todayRechargeCount)

		err = o.Raw(`
			SELECT IFNULL(SUM(ABS(amount)), 0) as total_amount, COUNT(*) as count 
			FROM ss_balance_log 
			WHERE type = 2 AND created_at BETWEEN ? AND ? AND is_deleted = 0
		`, startTime, endTime).QueryRow(&todayConsumeAmount, &todayConsumeCount)

		err = o.Raw(`
			SELECT IFNULL(SUM(balance), 0) as total_balance, COUNT(*) as count 
			FROM ss_member 
			WHERE is_deleted = 0
		`).QueryRow(&totalBalanceAmount, &memberCount)
	}

	// 返回统计数据
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取余额统计信息成功",
		"data": map[string]interface{}{
			"today_recharge_amount": todayRechargeAmount,
			"today_recharge_count":  todayRechargeCount,
			"today_consume_amount":  todayConsumeAmount,
			"today_consume_count":   todayConsumeCount,
			"total_balance_amount":  totalBalanceAmount,
			"member_count":          memberCount,
			"date":                  today,
		},
	}
	c.ServeJSON()
}
